package com.ruoyi.gateway.config;

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 可以打印项目中所涉及的过滤器以及启动顺序
 */
@Configuration
public class FilterOrderConfig {

    private final List<GlobalFilter> globalFilters;

    // 通过构造函数注入所有 GlobalFilter Bean
    public FilterOrderConfig(List<GlobalFilter> globalFilters) {
        this.globalFilters = globalFilters;
    }

    // 应用启动后执行
    @PostConstruct
    public void logFilterOrder() {
        globalFilters.forEach(filter -> {
            // 获取过滤器类名
            String filterName = filter.getClass().getSimpleName();
            // 获取过滤器执行顺序（若实现 Ordered 接口）
            int order = (filter instanceof Ordered) ? ((Ordered) filter).getOrder() : Ordered.LOWEST_PRECEDENCE;
            System.out.printf("GlobalFilter: %-30s → Order: %d%n", filterName, order);
        });
    }
}